<?php


namespace catchAdmin\apipatient\service;


use app\common\business\Message;
use app\common\lib\ZhyxMongo;
use catcher\exceptions\FailedException;
use MongoDB\BSON\ObjectId;

class HealthDiary
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\HealthDiary();
    }

    public function createHealthDiary(array $data, array $userInfo): bool
    {

        try {
            //根据患者id判断本年度是否已经上报数据
            $objectId = '';
            $year = (int)date("Y");
            $isExists = $this->model->where([["patientId", "=", $userInfo["patientId"]], ["year", "=", $year]])->find();
            if (empty($isExists)) {
                $objectId = $this->model->insertGetId([
                    'patientId' => $userInfo["patientId"],
                    'name' => $userInfo["name"],
                    'year' => $year,
                    'deleted_at' => 0,
                    'bloodSugar' => [],
                    'bloodPressure' => [],
                    'BMI' => []
                ]);
            } else {
                $objectId = $isExists["id"];
            }
            $data["date"] = date("Y-m-d");
            $data["time"] = date("H:i:s");
            $result = ZhyxMongo::getInstance()->setCollection('health_diary')->updateOne(["_id" => new ObjectId($objectId)], ['$push' => [
                $data["data_type"] => $data
            ]]);
            # 判断是否存在重度偏高
            if (isset($data["is_normal"]) && $data["is_normal"] === 0) {
                $item = "";
                switch ($data["data_type"]) {
                    case "bloodPressure":
                        $item = "血压";
                        break;
                    case "bloodSugar":
                        $item = "血糖";
                        break;
                    default:
                        $item = "体重";
                        break;
                }
                # 执行异常消息推送逻辑
                (new Message())->smsAbnormalInfo('Other', '', [$userInfo["patientId"]], $item);

            }
            return $result->getModifiedCount() > 0;
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }

    }

    public function getAHealthDiary(array $condition, array $userInfo): array
    {
        $cnd["year"] = (int)date("Y", strtotime($condition["start_date"]));
        $cnd["match"] = [];
        $dataType = $condition["data_type"] ?? "bloodSugar";
        $cnd["match"] = ['$and' => [[$dataType . '.date' => ['$gte' => $condition["start_date"], '$lte' => $condition["end_date"]]]]];
        if (isset($condition["timeFrame"]) && !empty($condition["timeFrame"])) {
            $cnd["match"]['bloodSugar.timeFrame'] = $condition["timeFrame"];
        }

        return $this->model->getAHealthDiary($dataType, $cnd, $userInfo);
    }

    public function getLastAHealthDiary(string $patientId)
    {
        return $this->model->getLastHealthDiary($patientId);
    }

    public function getHealRecordDetail(string $startDate, string $patientId, string $type): array
    {
        return $this->model->getHealthRecord($startDate, $patientId, $type);

    }

    public function getHealRecordList(string $startDate, string $endDate, string $patientId): array
    {
        $arr = [];
        $result = $this->model->getHealthList($startDate, $endDate, $patientId);
        if (!empty($result)) {
            foreach ($result as $k => $v) {
                $temp = [];
                $temp["date"] = $v["_id"];
                foreach ($v["detail"] as $dk => $dv) {
                    $temp["detail"][$dv["timeFrame"]] = $dv;
                }
                $arr[] = $temp;
            }
        }
        return $arr;
    }
}